{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1ljvLya59ep5"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VcQIa1uG86Wh"
      },
      "source": [
        "# DTensor concepts"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6dWNQEum9AfY"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/dtensor_overview\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/dtensor_overview.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/dtensor_overview.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/dtensor_overview.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MGZuakHVlVQf"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This colab introduces DTensor, an extension to TensorFlow for synchronous distributed computing.\n",
        "\n",
        "DTensor provides a global programming model that allows developers to compose applications that operate on Tensors globally while managing the distribution across devices internally. DTensor distributes the program and tensors according to the sharding directives through a procedure called *[Single program, multiple data (SPMD)](https://en.wikipedia.org/wiki/SPMD) expansion*.\n",
        "\n",
        "By decoupling the application from sharding directives, DTensor enables running the same application on a single device, multiple devices, or even multiple clients, while preserving its global semantics.\n",
        "\n",
        "This guide introduces DTensor concepts for distributed computing, and how DTensor integrates with TensorFlow. For a demo of using DTensor in model training, refer to the [Distributed training with DTensor](../tutorials/distribute/dtensor_ml_tutorial.ipynb) tutorial."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "h7ZTDq7KngwA"
      },
      "source": [
        "## Setup\n",
        "\n",
        "DTensor (`tf.experimental.dtensor`) has been part of TensorFlow since the 2.9.0 release.\n",
        "\n",
        "Begin by importing TensorFlow, `dtensor`, and configure TensorFlow to use 6 virtual CPUs. Even though this example uses virtual CPUs, DTensor works the same way on CPU, GPU or TPU devices."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Q92lo0zjwej8"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "from tensorflow.experimental import dtensor\n",
        "\n",
        "print('TensorFlow version:', tf.__version__)\n",
        "\n",
        "def configure_virtual_cpus(ncpu):\n",
        "  phy_devices = tf.config.list_physical_devices('CPU')\n",
        "  tf.config.set_logical_device_configuration(phy_devices[0], [\n",
        "        tf.config.LogicalDeviceConfiguration(),\n",
        "    ] * ncpu)\n",
        "\n",
        "configure_virtual_cpus(6)\n",
        "DEVICES = [f'CPU:{i}' for i in range(6)]\n",
        "\n",
        "tf.config.list_logical_devices('CPU')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O-lsrxUnlsCC"
      },
      "source": [
        "## DTensor's model of distributed tensors\n",
        "\n",
        "DTensor introduces two concepts: `dtensor.Mesh` and `dtensor.Layout`. They are abstractions to model the sharding of tensors across topologically related devices.\n",
        "\n",
        "- `Mesh` defines the device list for computation.\n",
        "- `Layout` defines how to shard the Tensor dimension on a `Mesh`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JjiHaH0ql9yo"
      },
      "source": [
        "### Mesh\n",
        "\n",
        "`Mesh` represents a logical Cartisian topology of a set of devices. Each dimension of the Cartisian grid is called a **Mesh dimension**, and referred to with a name. Names of mesh dimension within the same `Mesh` must be unique.\n",
        "\n",
        "Names of mesh dimensions are referenced by `Layout` to describe the sharding behavior of a `tf.Tensor` along each of its axes. This is described in more detail later in the section on `Layout`.\n",
        "\n",
        "`Mesh` can be thought of as a multi-dimensional array of devices."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_J6cOieEbaUw"
      },
      "source": [
        "In a 1 dimensional `Mesh`, all devices form a list in a single mesh dimension. The following example uses `dtensor.create_mesh` to create a mesh from 6 CPU devices along a mesh dimension `'x'` with a size of 6 devices:\n",
        "\n",
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_mesh_1d.png\" alt=\"A 1 dimensional mesh with 6 CPUs\" class=\"no-filter\">\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QLH5fgdBmA58"
      },
      "outputs": [],
      "source": [
        "mesh_1d = dtensor.create_mesh([('x', 6)], devices=DEVICES)\n",
        "print(mesh_1d)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hSZwaUwnEgXB"
      },
      "source": [
        "A `Mesh` can be multi dimensional as well. In the following example, 6 CPU devices form a `3x2` mesh, where the `'x'` mesh dimension has a size of 3 devices, and the `'y'` mesh dimension has a size of 2 devices:\n",
        "\n",
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_mesh_2d.png\" alt=\"A 2 dimensional mesh with 6 CPUs\"\n",
        "     class=\"no-filter\">"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "op6TmKUQE-sZ"
      },
      "outputs": [],
      "source": [
        "mesh_2d = dtensor.create_mesh([('x', 3), ('y', 2)], devices=DEVICES)\n",
        "print(mesh_2d)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "deAqdrDPFn2f"
      },
      "source": [
        "### Layout\n",
        "\n",
        "**`Layout`** specifies how a tensor is distributed, or sharded, on a `Mesh`.\n",
        "\n",
        "Note: In order to avoid confusions between `Mesh` and `Layout`, the term *dimension* is always associated with `Mesh`, and the term *axis* with `Tensor` and `Layout` in this guide.\n",
        "\n",
        "The rank of `Layout` should be the same as the rank of the `Tensor` where the `Layout` is applied. For each of the `Tensor`'s axes the `Layout` may specify a mesh dimension to shard the tensor across, or specify the axis as \"unsharded\".\n",
        "The tensor is replicated across any mesh dimensions that it is not sharded across.\n",
        "\n",
        "The rank of a `Layout` and the number of dimensions of a `Mesh` do not need to match. The `unsharded` axes of a `Layout` do not need to be associated to a mesh dimension, and `unsharded` mesh dimensions do not need to be associated with a `layout` axis.\n",
        "\n",
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_components_diag.png\" alt=\"Diagram of dtensor components.\"\n",
        "     class=\"no-filter\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Px_bF1c-bQ7e"
      },
      "source": [
        "Let's analyze a few examples of `Layout` for the `Mesh`'s created in the previous section."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fqzCNlWAbm-c"
      },
      "source": [
        "On a 1-dimensional mesh such as `[(\"x\", 6)]` (`mesh_1d` in the previous section), `Layout([\"unsharded\", \"unsharded\"], mesh_1d)` is a layout for a rank-2 tensor replicated across 6 devices.\n",
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_layout_replicated.png\" alt=\"A tensor replicated across a rank-1 mesh\" class=\"no-filter\">"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-a3EnmZag6x1"
      },
      "outputs": [],
      "source": [
        "layout = dtensor.Layout([dtensor.UNSHARDED, dtensor.UNSHARDED], mesh_1d)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ywRJwuLDt2Qq"
      },
      "source": [
        "Using the same tensor and mesh the layout `Layout(['unsharded', 'x'])` would shard the second axis of the tensor across the 6 devices.\n",
        "\n",
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_layout_rank1.png\" alt=\"A tensor sharded across a rank-1 mesh\" class=\"no-filter\">"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7BgqL0jUvV5a"
      },
      "outputs": [],
      "source": [
        "layout = dtensor.Layout([dtensor.UNSHARDED, 'x'], mesh_1d)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DgciDNmK76l9"
      },
      "source": [
        "Given a 2-dimensional 3x2 mesh such as `[(\"x\", 3), (\"y\", 2)]`, (`mesh_2d` from the previous section), `Layout([\"y\", \"x\"], mesh_2d)` is a layout for a rank-2 `Tensor` whose first axis is sharded across mesh dimension `\"y\"`, and whose second axis is sharded across mesh dimension `\"x\"`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Eyp_qOSyvieo"
      },
      "source": [
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_layout_rank2.png\" alt=\"A tensorr with its first axis sharded across mesh dimension 'y' and it's second axis sharded across mesh dimension 'x'\" class=\"no-filter\">\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p8OrehEuhPbS"
      },
      "outputs": [],
      "source": [
        "layout = dtensor.Layout(['y', 'x'], mesh_2d)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1Kyg0V3ehMNJ"
      },
      "source": [
        "For the same `mesh_2d`, the layout `Layout([\"x\", dtensor.UNSHARDED], mesh_2d)` is a layout for a rank-2 `Tensor` that is replicated across `\"y\"`, and whose first axis is sharded on mesh dimension `x`.\n",
        "\n",
        "<img src=\"https://www.tensorflow.org/images/dtensor/dtensor_layout_hybrid.png\" alt=\"A tensor replicated across mesh-dimension y, with its first axis sharded across mesh dimension 'x'\" class=\"no-filter\">\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IkWe6mVl7uRb"
      },
      "outputs": [],
      "source": [
        "layout = dtensor.Layout([\"x\", dtensor.UNSHARDED], mesh_2d)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TTalu6M-ISYb"
      },
      "source": [
        "### Single-client and multi-client applications\n",
        "\n",
        "DTensor supports both single-client and multi-client applications. The colab Python kernel is an example of a single client DTensor application, where there is a single Python process.\n",
        "\n",
        "In a multi-client DTensor application, multiple Python processes collectively perform as a coherent application. The Cartisian grid of a `Mesh` in a multi-client DTensor application can span across devices regardless of whether they are attached locally to the current client or attached remotely to another client. The set of all devices used by a `Mesh` are called the *global device list*.\n",
        "\n",
        "The creation of a `Mesh` in a multi-client DTensor application is a collective operation where the *global device list* is identical for all of the participating clients, and the creation of the `Mesh` serves as a global barrier.\n",
        "\n",
        "During `Mesh` creation, each client provides its *local device list* together with the expected *global device list*. DTensor validates that both lists are consistent. Please refer to the API documentation for `dtensor.create_mesh` and `dtensor.create_distributed_mesh`\n",
        " for more information on multi-client mesh creation and the *global device list*.\n",
        "\n",
        "Single-client can be thought of as a special case of multi-client, with 1 client. In a single-client application, the *global device list* is identical to the *local device list*.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "P_F7DWkXkB4w"
      },
      "source": [
        "## DTensor as a sharded tensor\n",
        "\n",
        "Now, start coding with `DTensor`. The helper function, `dtensor_from_array`, demonstrates creating DTensors from something that looks like a `tf.Tensor`. The function performs two steps:\n",
        "\n",
        "  - Replicates the tensor to every device on the mesh.\n",
        "  - Shards the copy according to the layout requested in its arguments."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s6aws-b8dN9L"
      },
      "outputs": [],
      "source": [
        "def dtensor_from_array(arr, layout, shape=None, dtype=None):\n",
        "  \"\"\"Convert a DTensor from something that looks like an array or Tensor.\n",
        "\n",
        "  This function is convenient for quick doodling DTensors from a known,\n",
        "  unsharded data object in a single-client environment. This is not the\n",
        "  most efficient way of creating a DTensor, but it will do for this\n",
        "  tutorial.\n",
        "  \"\"\"\n",
        "  if shape is not None or dtype is not None:\n",
        "    arr = tf.constant(arr, shape=shape, dtype=dtype)\n",
        "\n",
        "  # replicate the input to the mesh\n",
        "  a = dtensor.copy_to_mesh(arr,\n",
        "          layout=dtensor.Layout.replicated(layout.mesh, rank=layout.rank))\n",
        "  # shard the copy to the desirable layout\n",
        "  return dtensor.relayout(a, layout=layout)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r3o6IysrlGMu"
      },
      "source": [
        "### Anatomy of a DTensor\n",
        "\n",
        "A DTensor is a `tf.Tensor` object, but augumented with the `Layout` annotation that defines its sharding behavior. A DTensor consists of the following:\n",
        "\n",
        "  - Global tensor meta-data, including the global shape and dtype of the tensor.\n",
        "  - A `Layout`, which defines the `Mesh` the `Tensor` belongs to, and how the `Tensor` is sharded onto the `Mesh`.\n",
        "  - A list of **component tensors**, one item per local device in the `Mesh`.\n",
        "\n",
        "With `dtensor_from_array`, you can create your first DTensor, `my_first_dtensor`, and examine its contents:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mQu_nScGUvYH"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 6)], devices=DEVICES)\n",
        "layout = dtensor.Layout([dtensor.UNSHARDED], mesh)\n",
        "\n",
        "my_first_dtensor = dtensor_from_array([0, 1], layout)\n",
        "\n",
        "# Examine the DTensor content\n",
        "print(my_first_dtensor)\n",
        "print(\"global shape:\", my_first_dtensor.shape)\n",
        "print(\"dtype:\", my_first_dtensor.dtype)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r8LQy1nqmvFy"
      },
      "source": [
        "#### Layout and `fetch_layout`\n",
        "\n",
        "The layout of a DTensor is not a regular attribute of `tf.Tensor`. Instead, DTensor provides a function, `dtensor.fetch_layout` to access the layout of a DTensor:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dCSFyaAjmzGu"
      },
      "outputs": [],
      "source": [
        "print(dtensor.fetch_layout(my_first_dtensor))\n",
        "assert layout == dtensor.fetch_layout(my_first_dtensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ed7i3l2lmatm"
      },
      "source": [
        "#### Component tensors, `pack` and `unpack`\n",
        "\n",
        "A DTensor consists of a list of **component tensors**. The component tensor for a device in the `Mesh` is the `Tensor` object representing the piece of the global DTensor that is stored on this device.\n",
        "\n",
        "A DTensor can be unpacked into component tensors through `dtensor.unpack`. You can make use of `dtensor.unpack` to inspect the components of the DTensor, and confirm they are on all devices of the `Mesh`.\n",
        "\n",
        "Note that the positions of component tensors in the global view may overlap each other. For example, in the case of a fully replicated layout, all components are identical replicas of the global tensor."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BGbjqVAOnXMk"
      },
      "outputs": [],
      "source": [
        "for component_tensor in dtensor.unpack(my_first_dtensor):\n",
        "  print(\"Device:\", component_tensor.device, \",\", component_tensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-tqIQM52k788"
      },
      "source": [
        "As shown, `my_first_dtensor` is a tensor of `[0, 1]` replicated to all 6 devices."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6By3k-CGn3yv"
      },
      "source": [
        "The inverse operation of `dtensor.unpack` is `dtensor.pack`. Component tensors can be packed back into a DTensor.\n",
        "\n",
        "The components must have the same rank and dtype, which will be the rank and dtype of the returned DTensor. However, there is no strict requirement on the device placement of component tensors as inputs of `dtensor.unpack`: the function will automatically copy the component tensors to their respective corresponding devices.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9lT-6qQwxOgf"
      },
      "outputs": [],
      "source": [
        "packed_dtensor = dtensor.pack(\n",
        "    [[0, 1], [0, 1], [0, 1],\n",
        "     [0, 1], [0, 1], [0, 1]],\n",
        "     layout=layout\n",
        ")\n",
        "print(packed_dtensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zvS3autrpK2U"
      },
      "source": [
        "### Sharding a DTensor to a Mesh\n",
        "\n",
        "So far you've worked with the `my_first_dtensor`, which is a rank-1 DTensor fully replicated across a dim-1 `Mesh`.\n",
        "\n",
        "Next, create and inspect DTensors that are sharded across a dim-2 `Mesh`. The following example does this with a 3x2 `Mesh` on 6 CPU devices, where size of mesh dimension `'x'` is 3 devices, and size of mesh dimension`'y'` is 2 devices:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KWb9Ae0VJ-Rc"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 3), (\"y\", 2)], devices=DEVICES)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ndSeQSFWKQk9"
      },
      "source": [
        "#### Fully sharded rank-2 Tensor on a dim-2 Mesh\n",
        "\n",
        "Create a 3x2 rank-2 DTensor, sharding its first axis along the `'x'` mesh dimension, and its second axis along the `'y'` mesh dimension.\n",
        "\n",
        "- Because the tensor shape equals to the mesh dimension along all of the sharded axes, each device receives a single element of the DTensor.\n",
        "- The rank of the component tensor is always the same as the rank of the global shape. DTensor adopts this convention as a simple way to preserve information for locating the relation between a component tensor and the global DTensor."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ax_ZHouJp1MX"
      },
      "outputs": [],
      "source": [
        "fully_sharded_dtensor = dtensor_from_array(\n",
        "    tf.reshape(tf.range(6), (3, 2)),\n",
        "    layout=dtensor.Layout([\"x\", \"y\"], mesh))\n",
        "\n",
        "for raw_component in dtensor.unpack(fully_sharded_dtensor):\n",
        "  print(\"Device:\", raw_component.device, \",\", raw_component)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zhsLC-NgrC2p"
      },
      "source": [
        "#### Fully replicated rank-2 Tensor on a dim-2 Mesh\n",
        "\n",
        "For comparison, create a 3x2 rank-2 DTensor, fully replicated to the same dim-2 Mesh.\n",
        "\n",
        " - Because the DTensor is fully replicated, each device receives a full replica of the 3x2 DTensor.\n",
        " - The rank of the component tensors are the same as the rank of the global shape -- this fact is trivial, because in this case, the shape of the component tensors are the same as the global shape anyway."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xmyC6H6Ec90P"
      },
      "outputs": [],
      "source": [
        "fully_replicated_dtensor = dtensor_from_array(\n",
        "    tf.reshape(tf.range(6), (3, 2)),\n",
        "    layout=dtensor.Layout([dtensor.UNSHARDED, dtensor.UNSHARDED], mesh))\n",
        "# Or, layout=tensor.Layout.fully_replicated(mesh, rank=2)\n",
        "\n",
        "for component_tensor in dtensor.unpack(fully_replicated_dtensor):\n",
        "  print(\"Device:\", component_tensor.device, \",\", component_tensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KWoyv_oHMzk1"
      },
      "source": [
        "#### Hybrid rank-2 Tensor on a dim-2 Mesh\n",
        "\n",
        "What about somewhere between fully sharded and fully replicated?\n",
        "\n",
        "DTensor allows a `Layout` to be a hybrid, sharded along some axes, but replicated along others.\n",
        "\n",
        "For example, you can shard the same 3x2 rank-2 DTensor in the following way:\n",
        "\n",
        "  - 1st axis sharded along the `'x'` mesh dimension.\n",
        "  - 2nd axis replicated along the `'y'` mesh dimension.\n",
        "\n",
        "To achieve this sharding scheme, you just need to replace the sharding spec of the 2nd axis from `'y'` to `dtensor.UNSHARDED`, to indicate your intention of replicating along the 2nd axis. The layout object will look like `Layout(['x', dtensor.UNSHARDED], mesh)`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DygnbkQ1Lu42"
      },
      "outputs": [],
      "source": [
        "hybrid_sharded_dtensor = dtensor_from_array(\n",
        "    tf.reshape(tf.range(6), (3, 2)),\n",
        "    layout=dtensor.Layout(['x', dtensor.UNSHARDED], mesh))\n",
        "\n",
        "for component_tensor in dtensor.unpack(hybrid_sharded_dtensor):\n",
        "  print(\"Device:\", component_tensor.device, \",\", component_tensor)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T7FtZ9kQRZgE"
      },
      "source": [
        "You can inspect the component tensors of the created DTensor and verify they are indeed sharded according to your scheme. It may be helpful to illustrate the situation with a chart:\n",
        "\n",
        "  <img src=\"https://www.tensorflow.org/images/dtensor/dtensor_hybrid_mesh.png\" alt=\"A 3x2 hybrid mesh with 6 CPUs\"\n",
        "     class=\"no-filter\" width=75%>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "auAkA38XjL-q"
      },
      "source": [
        "#### Tensor.numpy() and sharded DTensor\n",
        "\n",
        "Be aware that calling the `.numpy()` method on a sharded DTensor raises an error. The rationale for erroring is to protect against unintended gathering of data from multiple computing devices to the host CPU device backing the returned NumPy array:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "hNdwmnL0jAXS"
      },
      "outputs": [],
      "source": [
        "print(fully_replicated_dtensor.numpy())\n",
        "\n",
        "try:\n",
        "  fully_sharded_dtensor.numpy()\n",
        "except tf.errors.UnimplementedError:\n",
        "  print(\"got an error as expected for fully_sharded_dtensor\")\n",
        "\n",
        "try:\n",
        "  hybrid_sharded_dtensor.numpy()\n",
        "except tf.errors.UnimplementedError:\n",
        "  print(\"got an error as expected for hybrid_sharded_dtensor\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8WcMkiagPF_6"
      },
      "source": [
        "## TensorFlow API on DTensor\n",
        "\n",
        "DTensor strives to be a drop-in replacement for tensor in your program. The TensorFlow Python API that consume `tf.Tensor`, such as the Ops library functions, `tf.function`, `tf.GradientTape`, also work with DTensor.\n",
        "\n",
        "To accomplish this, for each [TensorFlow Graph](https://www.tensorflow.org/guide/intro_to_graphs), DTensor produces and executes an equivalent [SPMD](https://en.wikipedia.org/wiki/SPMD) graph in a procedure called *SPMD expansion*. A few critical steps in DTensor SPMD expansion are:\n",
        "\n",
        "  - Propagating the sharding `Layout` of DTensor in the TensorFlow graph\n",
        "  - Rewriting TensorFlow Ops on the global DTensor with equivalent TensorFlow Ops on the component tensors, inserting collective and communication Ops when necessary\n",
        "  - Lowering backend neutral TensorFlow Ops to backend specific TensorFlow Ops.\n",
        "\n",
        "The final result is that **DTensor is a drop-in replacement for Tensor**.\n",
        "\n",
        "Note: DTensor is still an experimental API which means you will be exploring and pushing the boundaries and limits of the DTensor programming model.\n",
        "\n",
        "There are 2 ways of triggering DTensor execution:\n",
        "\n",
        "  - DTensor as operands of a Python function, such as `tf.matmul(a, b)`, will run through DTensor if `a`, `b`, or both are DTensors.\n",
        "  - Requesting the result of a Python function to be a DTensor, such as `dtensor.call_with_layout(tf.ones, layout, shape=(3, 2))`, will run through DTensor because we requested the output of `tf.ones` to be sharded according to a `layout`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "urKzmqAoPssT"
      },
      "source": [
        "### DTensor as operands\n",
        "\n",
        "Many TensorFlow API functions take `tf.Tensor` as their operands, and returns `tf.Tensor` as their results. For these functions, you can express intention to run a function through DTensor by passing in DTensor as operands. This section uses `tf.matmul(a, b)` as an example."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7LO8ZT7iWVga"
      },
      "source": [
        "#### Fully replicated input and output\n",
        "\n",
        "In this case, the DTensors are fully replicated. On each of the devices of the `Mesh`,\n",
        "  - the component tensor for operand `a` is `[[1, 2, 3], [4, 5, 6]]` (2x3)\n",
        "  - the component tensor for operand `b` is `[[6, 5], [4, 3], [2, 1]]` (3x2)\n",
        "  - the computation consists of a single `MatMul` of `(2x3, 3x2) -> 2x2`,\n",
        "  - the component tensor for result `c` is `[[20, 14], [56,41]]` (2x2)\n",
        "\n",
        "Total number of floating point mul operations is `6 device * 4 result * 3 mul = 72`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TiZf2J9JNd2D"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 6)], devices=DEVICES)\n",
        "layout = dtensor.Layout([dtensor.UNSHARDED, dtensor.UNSHARDED], mesh)\n",
        "a = dtensor_from_array([[1, 2, 3], [4, 5, 6]], layout=layout)\n",
        "b = dtensor_from_array([[6, 5], [4, 3], [2, 1]], layout=layout)\n",
        "\n",
        "c = tf.matmul(a, b) # runs 6 identical matmuls in parallel on 6 devices\n",
        "\n",
        "# `c` is a DTensor replicated on all devices (same as `a` and `b`)\n",
        "print('Sharding spec:', dtensor.fetch_layout(c).sharding_specs)\n",
        "print(\"components:\")\n",
        "for component_tensor in dtensor.unpack(c):\n",
        "  print(component_tensor.device, component_tensor.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QXtR9qgKWgWV"
      },
      "source": [
        "#### Sharding operands along the contracted axis\n",
        "\n",
        "You can reduce the amount of computation per device by sharding the operands `a` and `b`. A popular sharding scheme for `tf.matmul` is to shard the operands along the axis of the contraction, which means sharding `a` along the second axis, and `b` along the first axis.\n",
        "\n",
        "The global matrix product sharded under this scheme can be performed efficiently, by local matmuls that runs concurrently, followed by a collective reduction to aggregate the local results. This is also the [canonical way](https://github.com/open-mpi/ompi/blob/ee87ec391f48512d3718fc7c8b13596403a09056/docs/man-openmpi/man3/MPI_Reduce.3.rst?plain=1#L265) of implementing a distributed matrix dot product.\n",
        "\n",
        "Total number of floating point mul operations is `6 devices * 4 result * 1 = 24`, a factor of 3 reduction compared to the fully replicated case (72) above. The factor of 3 is due to the sharding along `x` mesh dimension with a size of `3` devices.\n",
        "\n",
        "The reduction of the number of operations run sequentially is the main mechansism with which synchronuous model parallelism accelerates training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EyVAUvMePbms"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 3), (\"y\", 2)], devices=DEVICES)\n",
        "a_layout = dtensor.Layout([dtensor.UNSHARDED, 'x'], mesh)\n",
        "a = dtensor_from_array([[1, 2, 3], [4, 5, 6]], layout=a_layout)\n",
        "b_layout = dtensor.Layout(['x', dtensor.UNSHARDED], mesh)\n",
        "b = dtensor_from_array([[6, 5], [4, 3], [2, 1]], layout=b_layout)\n",
        "\n",
        "c = tf.matmul(a, b)\n",
        "# `c` is a DTensor replicated on all devices (same as `a` and `b`)\n",
        "print('Sharding spec:', dtensor.fetch_layout(c).sharding_specs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IhD8yYgJiCEh"
      },
      "source": [
        "#### Additional sharding\n",
        "\n",
        "You can perform additional sharding on the inputs, and they are appropriately carried over to the results. For example, you can apply additional sharding of operand `a` along its first axis to the `'y'` mesh dimension. The additional sharding will be carried over to the first axis of the result `c`.\n",
        "\n",
        "Total number of floating point mul operations is `6 devices * 2 result * 1 = 12`, an additional factor of 2 reduction compared to the case (24) above. The factor of 2 is due to the sharding along `y` mesh dimension with a size of `2` devices."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0PYqe0neiOpR"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 3), (\"y\", 2)], devices=DEVICES)\n",
        "\n",
        "a_layout = dtensor.Layout(['y', 'x'], mesh)\n",
        "a = dtensor_from_array([[1, 2, 3], [4, 5, 6]], layout=a_layout)\n",
        "b_layout = dtensor.Layout(['x', dtensor.UNSHARDED], mesh)\n",
        "b = dtensor_from_array([[6, 5], [4, 3], [2, 1]], layout=b_layout)\n",
        "\n",
        "c = tf.matmul(a, b)\n",
        "# The sharding of `a` on the first axis is carried to `c'\n",
        "print('Sharding spec:', dtensor.fetch_layout(c).sharding_specs)\n",
        "print(\"components:\")\n",
        "for component_tensor in dtensor.unpack(c):\n",
        "  print(component_tensor.device, component_tensor.numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c-1NazCVmLWZ"
      },
      "source": [
        "### DTensor as output\n",
        "\n",
        "What about Python functions that do not take operands, but returns a Tensor result that can be sharded? Examples of such functions are:\n",
        "\n",
        "  - `tf.ones`, `tf.zeros`, `tf.random.stateless_normal`\n",
        "\n",
        "For these Python functions, DTensor provides `dtensor.call_with_layout` which eagerly executes a Python function with DTensor, and ensures that the returned Tensor is a DTensor with the requested `Layout`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "J0jo_8NPtJiO"
      },
      "outputs": [],
      "source": [
        "help(dtensor.call_with_layout)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "V-YdLvfytM7g"
      },
      "source": [
        "The eagerly executed Python function usually only contain a single non-trivial TensorFlow Op.\n",
        "\n",
        "To use a Python function that emits multiple TensorFlow Ops with `dtensor.call_with_layout`, the function should be converted to a `tf.function`. Calling a `tf.function` is a single TensorFlow Op. When the `tf.function` is called, DTensor can perform layout propagation when it analyzes the computing graph of the `tf.function`, before any of the intermediate tensors are materialized."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DLrksgFjqRLS"
      },
      "source": [
        "#### APIs that emit a single TensorFlow Op\n",
        "\n",
        "If a function  emits a single TensorFlow Op, you can directly apply `dtensor.call_with_layout` to the function:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "G1CuKYSFtFeM"
      },
      "outputs": [],
      "source": [
        "help(tf.ones)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2m_EAwy-ozOh"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 3), (\"y\", 2)], devices=DEVICES)\n",
        "ones = dtensor.call_with_layout(tf.ones, dtensor.Layout(['x', 'y'], mesh), shape=(6, 4))\n",
        "print(ones)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bx-7Xo8Cpb8S"
      },
      "source": [
        "#### APIs that emit multiple TensorFlow Ops\n",
        "\n",
        "If the API emits multiple TensorFlow Ops, convert the function into a single Op through `tf.function`. For example, `tf.random.stateleess_normal`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "H8BQSTRFtCih"
      },
      "outputs": [],
      "source": [
        "help(tf.random.stateless_normal)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TvP81eYopSPm"
      },
      "outputs": [],
      "source": [
        "ones = dtensor.call_with_layout(\n",
        "    tf.function(tf.random.stateless_normal),\n",
        "    dtensor.Layout(['x', 'y'], mesh),\n",
        "    shape=(6, 4),\n",
        "    seed=(1, 1))\n",
        "print(ones)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qKoojp9ZyWzW"
      },
      "source": [
        "Wrapping a Python function that emits a single TensorFlow Op with `tf.function` is allowed. The only caveat is paying the associated cost and complexity of creating a `tf.function` from a Python function."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LbAtKrSkpOaq"
      },
      "outputs": [],
      "source": [
        "ones = dtensor.call_with_layout(\n",
        "    tf.function(tf.ones),\n",
        "    dtensor.Layout(['x', 'y'], mesh),\n",
        "    shape=(6, 4))\n",
        "print(ones)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "D-m1816JP3CE"
      },
      "source": [
        "### From `tf.Variable` to `dtensor.DVariable`\n",
        "\n",
        "In Tensorflow, `tf.Variable` is the holder for a mutable `Tensor` value.\n",
        "With DTensor, the corresponding variable semantics is provided by `dtensor.DVariable`.\n",
        "\n",
        "The reason a new type `DVariable` was introduced for DTensor variable is because DVariables have an additional requirement that the layout cannot change from its initial value."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "awRPuR26P0Sc"
      },
      "outputs": [],
      "source": [
        "mesh = dtensor.create_mesh([(\"x\", 6)], devices=DEVICES)\n",
        "layout = dtensor.Layout([dtensor.UNSHARDED, dtensor.UNSHARDED], mesh)\n",
        "\n",
        "v = dtensor.DVariable(\n",
        "    initial_value=dtensor.call_with_layout(\n",
        "        tf.function(tf.random.stateless_normal),\n",
        "        layout=layout,\n",
        "        shape=tf.TensorShape([64, 32]),\n",
        "        seed=[1, 1],\n",
        "        dtype=tf.float32))\n",
        "\n",
        "print(v.handle)\n",
        "assert layout == dtensor.fetch_layout(v)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Pb9jn473prC_"
      },
      "source": [
        "Other than the requirement on matching the `layout`, a `DVariable` behaves the same as a `tf.Variable`. For example, you can add a DVariable to a DTensor,\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "adxFw9wJpqQQ"
      },
      "outputs": [],
      "source": [
        "a = dtensor.call_with_layout(tf.ones, layout=layout, shape=(64, 32))\n",
        "b = v + a # add DVariable and DTensor\n",
        "print(b)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QxBdNHWSu-kV"
      },
      "source": [
        "You can also assign a DTensor to a DVariable:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oYwfiyw5P94U"
      },
      "outputs": [],
      "source": [
        "v.assign(a) # assign a DTensor to a DVariable\n",
        "print(a)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4fvSk_VUvGnj"
      },
      "source": [
        "Attempting to mutate the layout of a `DVariable`, by assigning a DTensor with an incompatible layout produces an error:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3pckUugYP_r-"
      },
      "outputs": [],
      "source": [
        "# variable's layout is immutable.\n",
        "another_mesh = dtensor.create_mesh([(\"x\", 3), (\"y\", 2)], devices=DEVICES)\n",
        "b = dtensor.call_with_layout(tf.ones,\n",
        "                     layout=dtensor.Layout([dtensor.UNSHARDED, dtensor.UNSHARDED], another_mesh),\n",
        "                     shape=(64, 32))\n",
        "try:\n",
        "  v.assign(b)\n",
        "except:\n",
        "  print(\"exception raised\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3LadIcwRvR6f"
      },
      "source": [
        "## What's next?\n",
        "\n",
        "In this colab, you learned about DTensor, an extension to TensorFlow for distributed computing. To try out these concepts in a tutorial, check out [Distributed training with DTensor](../tutorials/distribute/dtensor_ml_tutorial.ipynb)."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "dtensor_overview.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
